import random


from django.conf import settings
from django.core.validators import RegexValidator
from django.http import JsonResponse
from django.shortcuts import render,redirect,HttpResponse
from django_redis import get_redis_connection

from web import models
from utils.encrypt import md5
from utils import tencent
from utils.response import BaseResponse
from web.forms.account import LoginForm,MobileForm,SmsLoginForm



def login(request):
    if request.method == 'GET':
        form = LoginForm()
        #print('form',form)
        return render(request,'login.html',{'form':form})

    form = LoginForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'login.html', {'form': form})

    # print(form.cleaned_data)
    # print(request.POST)
    # print(request.POST.get('username'))
    # print(request.POST.getlist('password'))
    username = request.POST.get('username')
    password = request.POST.get('password')
    pwd = form.cleaned_data.get('password')
    # password = md5(password)  #在form中的对应的钩子方法中返回的时候，已经做了加密处理
    data_dict = form.cleaned_data
    role = data_dict.pop('role')
    # role = request.POST.get('role')
    #print(username,password,role,pwd,form.cleaned_data,data_dict)

    mapping = {"1":"ADMIN","2":"CUSTOMER"}
    #以下不用做判断，因为在LoginForm中已经做了判断
    # if role not in mapping:
    #     form.add_error('role','角色不存在')
    #     return render(request,'login.html',{'form':form})


    # if role == 1:
    #     user_object =  models.Administrator.objects.filter(active=1,username=username,password=password).first()
    #
    # else:
    #     user_object = models.Customer.objects.filter(active=1,username=username,password=password).first()
    if role == '1':
        user_object =  models.Administrator.objects.filter(active=1,**data_dict).first()

    else:
        user_object = models.Customer.objects.filter(active=1,**data_dict).first()

    print(user_object)

    #2.1校验失败
    if not user_object:
        form.add_error('username','用户名或密码错误')
        return render(request,'login.html',{'form':form})

    #2.2校验成功，用户信息写入session，进入项目后台
    request.session[settings.C_SESSION_KEY] = {'role':mapping[role],'name':user_object.username,'id':user_object.id}
    return redirect(settings.LOGIN_HOME)




def sms_login(request):
    if request.method == 'GET':
        form = SmsLoginForm()
        return render(request,'sms_login.html',{'form':form})

    #1.手机格式校验
    res = BaseResponse()
    form = SmsLoginForm(data=request.POST)
    if not form.is_valid():
        res.detail = form.errors
        return JsonResponse(res.dict,json_dumps_params={'ensure_ascii':False})

    # #2.短信验证码   #写在对应的Form的clean方法中
    # mobile = form.cleaned_data['mobile']
    # code = form.cleaned_data['code']
    # role = form.cleaned_data['role']
    #
    # conn=get_redis_connection('default')
    # redis_code = conn.get(mobile)
    # if not redis_code:
    #     res.detail = {'code':["短信验证码未发送或失效"]}
    #     return JsonResponse(res.dict)
    #
    # if code != redis_code.decode('utf-8'):
    #     res.detail = {'code': ["短信验证码错误"]}
    #     return JsonResponse(res.dict)

    #3.登录成功 + 注册 （检测手机号时候存在）
    # -未注册，自动注册
    # -已注册，直接登录
    role = form.cleaned_data['role']
    mobile = form.cleaned_data['mobile']
    if role == '1':
        user_object = models.Administrator.objects.filter(active=1,mobile=mobile).first()
    else:
        user_object = models.Customer.objects.filter(active=1,mobile=mobile).first()

    if not user_object:
        res.detail = {'mobile':['手机号不存在']}
        return JsonResponse(res.dict)

    #2.2校验成功，用户信息写入session+进入项目后台
    mapping = {'1':'ADMIN','2':'CUSTOMER'}
    request.session[settings.C_SESSION_KEY] = {'role':mapping[role],'name':user_object.username,'id':user_object.id}
    res.status = True
    res.data = settings.LOGIN_HOME
    return JsonResponse(res.dict)





def sms_send(request):
    print('request.POST数据: ',request.POST)
    res = BaseResponse()

    #1.校验手机号的格式
    form = MobileForm(data=request.POST)
    if not form.is_valid():
        # print(form.errors)
        print(form.errors.as_json())
        # print(form.errors.as_data())
        return JsonResponse({'status':False,'detail':form.errors},json_dumps_params={'ensure_ascii':False})
    # #1.1校验数据库的存在  #写在对应Form的钩子函数里面了
    # mobile = form.cleaned_data['mobile']
    # role = form.cleaned_data['role']
    # if role == '1':
    #     exists = models.Administrator.objects.filter(active=1,mobile=mobile).exists()
    # else:
    #     exists = models.Customer.objects.filter(active=1,mobile=mobile).exists()
    # if not exists:
    #     res.detail = {'mobile':['手机号不存在']}
    #     return JsonResponse(res.dict,json_dumps_params={'ensure_ascii':False})


    # #2.发送短信+生成验证码
    # mobile = form.cleaned_data['mobile']
    # sms_code = random.randint(100000,999999)
    # is_success = tencent.send_sms(mobile,str(sms_code))
    # if not is_success:
    #     return JsonResponse({'status': False, 'detail':{'mobile':['发送失败，请稍后重试']}}, json_dumps_params={'ensure_ascii': False})

    # #3.将手机号和验证码保存（以便下次验证）
    # conn = get_redis_connection('default')
    # conn.set(mobile,str(sms_code),ex=60)

    return JsonResponse({'status':True})


def home(request):


    return render(request, 'home.html')